const Koa = require('koa')
const _ = require('lodash')
const app = new Koa()
const koaBody = require('koa-body');
const mongoose = require('mongoose')
const error = require('koa-json-error')
const path = require('path')
var cors = require('koa-cors')
const koaStatic = require('koa-static')

const register_route = require('./routes')
const { connectionStr } = require('./config');

mongoose.connect(connectionStr, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false 
})

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => console.log('数据库链接成功'))

let options = {
    // Avoid showing the stacktrace in 'production' env
    postFormat: (e, obj) => process.env.NODE_ENV === 'production' ? _.omit(obj, 'stack') : obj
};
app.use(error(options))

// 跨域
app.use(cors());

app.use(koaStatic(path.join(__dirname, 'public')))
app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.join(__dirname, '/public/uploads'),
        keepExtensions: true
    }
}));

register_route(app)

app.listen(3000, () => {
    console.log('服务已启动')
})
